import gradio as gr


from GuiTab.Tab_image_upscale_batch import Tab_image_upscale_batch
from GuiTab.Tab_image_scaling_batch import Tab_image_scaling_batch
try:
    from GuiTab.Tab_JoyCaption2_batch import Tab_JoyCaption2_batch
except ImportError:
    Tab_JoyCaption2_batch = None
try:
    from GuiTab.Tab_LoRA_test import Tab_LoRA_test
except ImportError:
    Tab_LoRA_test = None
try:
    from GuiTab.Tab_home_page import Tab_home_page
except ImportError:
    Tab_home_page = None
try:
    from GuiTab.Tab_canny_redux import Tab_canny_redux
except ImportError:
    Tab_canny_redux = None
try:
    from GuiTab.Tab_redux_LoRA import Tab_redux_LoRA
except ImportError:
    Tab_redux_LoRA = None
try:
    from GuiTab.Tab_fill_LoRA import Tab_fill_LoRA
except ImportError:
    Tab_fill_LoRA = None
from GuiTab.Tab_text_to_image import Tab_text_to_image
from GuiTab.Tab_image_to_image import Tab_image_to_image




# 创建Gradio应用
def create_app():
    """创建Gradio应用"""
    with gr.Blocks() as demo:
        with gr.Tabs():
            if Tab_home_page is not None:
                with gr.Tab("首页"):
                        Tab_home_page()
            with gr.Tab("文本生图（FLUX1）"):
                    Tab_text_to_image()
            with gr.Tab("图生图（FLUX1）"):
                    Tab_image_to_image()
            with gr.Tab("批量图片高清放大"):
                    Tab_image_upscale_batch()
            with gr.Tab("批量图片比例缩放"):
                    Tab_image_scaling_batch()
            if Tab_JoyCaption2_batch is not None:
                with gr.Tab("批量提示词打标"):
                        Tab_JoyCaption2_batch()
            if Tab_LoRA_test is not None:
                with gr.Tab("LoRA测试"):
                        Tab_LoRA_test()
            if Tab_canny_redux is not None:
                with gr.Tab("根据结构参考图设计"):
                        Tab_canny_redux()
            if Tab_redux_LoRA is not None:
                with gr.Tab("根据LoRA模型和参考图设计"):
                        Tab_redux_LoRA()
            if Tab_fill_LoRA is not None:
                with gr.Tab("加载LoRA局部重新设计"):
                        Tab_fill_LoRA()

    return demo

# 创建全局demo对象
demo = create_app()

def main():
    """主函数"""
    try:
        from config.config import get_output_path, get_lora_dir_path, get_checkpoint_dir_path, get_input_path
        
        # 启动服务器并自动打开浏览器
        demo.launch(
            allowed_paths=[get_output_path(), get_lora_dir_path(), get_checkpoint_dir_path(), get_input_path()],
            share=False,
            inbrowser=True  # 自动在浏览器中打开
        )
    except Exception as e:
        print(f"启动失败: {e}")
        # 尝试基本启动
        demo.launch(share=False, inbrowser=True)

def run():
    """备用启动函数"""
    main()

if __name__ == "__main__":
    main()